/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package FileBrowser;

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.media.*;
import javax.microedition.media.control.VideoControl;
import javax.microedition.io.file.*;
import java.io.*;
import javax.microedition.io.*;

import javax.microedition.amms.*;
import javax.microedition.amms.control.*;
import javax.microedition.amms.control.imageeffect.*;


/**
 *
 * @author thomas.s
 */
public class MediaPlayer implements PlayerListener {

    MIDlet parent = null;
    ScreenSaver saver = null;
    MediaBrowser browser = null;
    public String path;
    public String curr;
    public String interpret="";
    public String title="";
    public String content="";
    public String mime="";
    Player player=null;
    VideoControl vc=null;
    Image bg=null;
    public String sPos="";

    public double duration=0, mduration=0, position=0;
    public boolean paused=true, enabled=false;
   
    MediaPlayer( MIDlet p )
    {
        parent = p;
        saver = new ScreenSaver(this);
    }

    public void vibrate()
    {
        Display.getDisplay(parent).vibrate(10);
    }

    public void endScreenSaver()
    {
        Display.getDisplay(parent).setCurrent(browser);
    }

    public void setScreenSaver()
    {
        Display.getDisplay(parent).setCurrent(saver);
    }

    void readMP3Tag( DataInputStream st )
    {
        content = "";
        if (st!=null)
        try {
            byte [] h = new byte[11]; int len,i; byte typ; char c; String tag, text;
            st.read(h, 0, 10);
            if ( h[0]==0x49 && h[1]==0x44 && h[2]==0x33)
            {
                int n=0, cn=0;
                while ( n<0x800 && cn<10 )
                {
                    st.read(h,0,10);
                    if (h[0]==0) break; cn++;
                    tag="";text="";
                    for ( i=0; i<4; i++ ) tag = tag + (char)(h[i]);
                    len = h[7] + (int)(h[6])*256;
                    if (h[6]!=0 || len==0) break;
                    content = content + "," + tag;
                    typ = st.readByte();
                    if (typ==0) { for ( i=1; i<len; i++ ) text = text + (char)(st.readByte()); }
                    else for ( i=1; i<len; i++ ) st.readByte();

                    if (tag.equals("TPE1")) interpret = text; else
                    if (tag.equals("TIT2")) title = text; else
                    if (tag.equals("TCON")) content = text; else
                    if (tag.equals("TLEN")) mduration = Double.parseDouble(text); else
                        ;

                    n = n+len+10;
                }
            }
            st.close();
            st = null;
        } catch( IOException io ){ interpret="exp"; }
    }

    public boolean open( MediaBrowser b, String name, String fName )
    {
        browser=b;
        curr=name;
        path=fName;
        sPos="--:--";
        if (vc!=null) vc.setVisible(false);
        
        boolean img=false, imgB=false;
        boolean aud=false, mp3=false;
        FileConnection fc=null;
        InputStream is=null;
        String check = curr.toLowerCase();
        try {
           fc = (FileConnection) Connector.open (path);
          // is = (InputStream)fc.openInputStream();
        } catch(IOException e) { return false; }


        if (check.endsWith(".mp3")) { mime="audio/mp3"; aud=true; mp3=true; } else
        if (check.endsWith(".wav")) { mime="audio/x-wav"; aud=true; } else
        if (check.endsWith(".mid")) { mime="audio/midi"; aud=true; } else
        if (check.endsWith(".amr")) { mime="audio/amr"; aud=true; } else
        if (check.endsWith(".3gp")) mime="video/3gpp"; else
        if (check.endsWith(".wmv")) mime="video/x-ms-wmv"; else
        if (check.endsWith(".avi")) mime="video/dx50"; else
        if (check.endsWith(".avi")) mime="video/x-divx"; else
        if (check.endsWith(".mp4")) mime="video/mp4"; else
        if (check.endsWith(".jpg")||check.endsWith(".jpeg")) 
        { mime="image/jpeg";
          //try { imgB=(fc.fileSize()>100000); } catch(Exception e) { imgB=false; }
          img=true;
        } else
        if (check.endsWith(".png")) { mime="image/png"; img=true; } else
        if (check.endsWith(".gif")) { mime="image/gif"; img=true; } else
        if (check.endsWith(".tif")) { mime="image/tiff"; img=true; } else
        if (check.endsWith(".bmp")) { mime="image/bmp"; img=true; } else
        mime="video/mpeg";

        if (player!=null) {
            try {
                player.stop();
                player.deallocate();
                player.close();
            } catch(MediaException e) {}
        }
        System.gc();
        bg = null;
        interpret="";
        title="";
        content="";
        mduration=0;

       // if (mp3) try { readMP3Tag( fc.openDataInputStream() ); } catch( IOException e) {}
        try {
           is = (InputStream)fc.openInputStream();
        } catch(IOException e) { return false; }

        if (aud)
        {
            if (player!=null) {
                try { player.stop(); } catch( Exception e ) {}
                player.deallocate();
                player.close();
            }
            try { Thread.sleep(200); } catch (InterruptedException ie) {}
            try {
                player = Manager.createPlayer(is,mime);
                player.setLoopCount(1);
                player.realize();
                player.addPlayerListener(this);
                player.prefetch();
                player.start();

                is.close(); fc.close();
            } catch( Exception e ) { player=null; }
            paused = false;
            duration = 0;
            position = 0;
            try { Thread.sleep(200); } catch (InterruptedException ie) {}

            if (browser!=null) browser.startAudio();
            enabled = true;
            return true;
        }


        if (img)
        {
            if (!imgB)
            {try { bg = Image.createImage(is); } catch(Exception e) { bg=null; }
            if (bg!=null)
            {
                player = null;
                vc = null;
                if (browser!=null) browser.startImage(bg,null);
                enabled = true;
                try { is.close(); fc.close(); } catch( IOException e) {}

                return true;
            }
            }
            else
            {
            // try scale down:
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            try {
                duration = 10;
               // is.reset();
                MediaProcessor mp = GlobalManager.createMediaProcessor(mime);
                duration = 20;
                mp.setInput(is,(int)fc.fileSize());
                duration = 30;
                mp.setOutput(out);
                duration = 40;
                ImageFormatControl fct = (ImageFormatControl)mp.getControl("javax.microedition.amms.control.ImageFormatControl");
                duration = 50;
                if (fct!=null) {
                    duration = 60;
                    fct.setFormat("image/jpeg");
                }
                duration = 70;
                ImageTransformControl tc = (ImageTransformControl)mp.getControl("javax.microedition.amms.control.imageeffect.ImageTransformControl");
                if (tc!=null) {
                    duration = 75;
                    int w = tc.getSourceWidth();
                    int h = tc.getSourceHeight();
                    tc.setSourceRect(0,0,w,h);
                    tc.setTargetSize(480,360,0);
                   // tc.setEnabled(true);
                }
                duration = 90;
                mp.start();
                duration = 100;
                mp.complete();
                duration = 110;
                byte [] data = out.toByteArray();
                duration = 120;
                if (data!=null) bg = Image.createImage(data,0,data.length);
                duration = 130;

            } catch(Exception e) { bg=null; }
            if (browser!=null && bg!=null) browser.startImage(bg,null);

            try { is.close(); fc.close(); } catch( IOException e) {}
            }
            return bg!=null;

        }



        // TODO: AVI/DIVX?
        Player p=null;
        try {
            p = Manager.createPlayer(is,mime);
            p.setLoopCount(1);
            p.realize();
            p.prefetch();
            is.close(); fc.close();

        } catch( Exception e ) { p=null; }
        if (p==null) return false;

        player = p;
        paused = false;
        duration = 0;
        position = 0;

        if ((vc = (VideoControl)player.getControl("VideoControl")) != null)
        {
            try {
                if (browser!=null) browser.startVideo(vc);
                //vc.initDisplayMode(vc.USE_DIRECT_VIDEO, this);
                //vc.setDisplaySize(480,400);
                //vc.setDisplayLocation(0,0);
                player.addPlayerListener(this);
                player.start();
                vc.setVisible(true);
            }
            catch( MediaException e) { if (browser!=null) browser.close(); return false; }
            try { Thread.sleep(200); } catch (InterruptedException ie) {}

            return true;
        }
        return false;
    }

    void close()
    {
        enabled = false;
        browser = null;
        if (player!=null) {
            try {
                //if (vc!=null) { vc.setVisible(false);vc=null; }
                if (player.getState()>=Player.REALIZED) player.deallocate();
                player.close();
            } catch ( Exception e ){}
            player = null;
        }
    }

    public void playerUpdate( Player p, String cmd, Object obj) {
        //if (p!=null && p.getState()==Player.REALIZED) enabled = true; else
        if (p!=null && p.getState()==Player.UNREALIZED) enabled = false; else
        if (p!=null && p.getState()==Player.STARTED)
        {
            long dur = player.getDuration();

            if (browser!=null) browser.startPlaying(dur==Player.TIME_UNKNOWN ? mduration : ((double)(player.getDuration())) / 1000000);
            enabled = true;
        } else
        if (cmd!=null)
        {
            if (cmd.equals("endOfMedia")) if (browser!=null) browser.next();
        }
    }

    public boolean videoRunning()
    {
        return vc!=null && enabled;
    }

    public double pos()
    {
        if (player!=null)
        {
            position = ((double)(player.getMediaTime())) / 1000000;
            int mm = (int)(position/60);
            int ss = (int)(position) % 60;
            sPos = "" + (mm/10) + (mm%10) + ":" + (ss/10) + (ss%10);
        }
        else
        {
            position = 0; sPos = "--:--";
        }
        return position;
    }

    public void setPos( double rel )
    {
        if (player!=null)
        {
            try { player.setMediaTime( (long)((duration*rel)*1000000) ); } catch(MediaException e) {}
            try { Thread.sleep(200); } catch (InterruptedException ie) {}
        }
    }

    public void pause()
    {
        if (player!=null) try {
            if (paused)
            {
                player.start();
            } else
            {
                player.stop();
                //vc.setVisible(false);
            }
            paused = !paused;
        } catch(MediaException e) {}
    }
}
